<?php

/**
 * A utility for handling internationalization (i18n)
 *
 * @author		Jason Orrill <jorrill@uga.edu>
 */

Class Framework_Util_I18n {

	public $langPreference ;
	private $translationTable ; 

	public function __construct() {

		$this->langPreference = I18N_DEFAULT_LANGUAGE ;
		$this->translationTable = array() ;

		if ( isset( $_SESSION[ I18N_PREFERENCE_NAME ] ) && !empty( $_SESSION[ I18N_PREFERENCE_NAME ] )) {
			$this->langPreference = $_SESSION[ I18N_PREFERENCE_NAME ] ;

		} elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
			$browserlangs = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

			if ( is_array( $browserlangs )) {
				//The choices are in the format 'abbreviation;number', we just want the first part.
				$tmp = explode( ';', $browserlangs[0] ) ;
				$this->langPreference = substr($tmp[0], 0, 2);
			}
		}
		
		if ( file_exists( APPLICATION_BASE_PATH . '/i18n.ini' )) {
			$this->translationTable = parse_ini_file( APPLICATION_BASE_PATH . '/i18n.ini', true ) ;
		}
		
		
	}
	
	
	public function setLanguage( $langCode ) {
		$this->langPreference = $langCode ;
		$_SESSION[ I18N_PREFERENCE_NAME ] = $langCode ;
	}

	public function translate( $key ) {
		$_output = '' ;

		if ( isset( $this->translationTable[ $this->langPreference ] )) {
			if ( isset( $this->translationTable[ $this->langPreference ][ $key ] )) {
				$_output = $this->translationTable[ $this->langPreference ][ $key ] ;
			} else {
				$_output = Framework_ErrorHandler::raiseError( "'$key' does not exist for language '" . $this->langPreference . "'", __METHOD__."::".__LINE__ ) ;
			}
		} else {
			$_output = Framework_ErrorHandler::raiseError( "Language '" . $this->langPreference . "' does not exist in i18n translation table", __METHOD__."::".__LINE__ ) ;
		}
		
		return $_output ;
	}

}

?>